package com.xmkj.winmoney.my;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.common.cons.Constans;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.retrofit.entity.result.UpLoadPicEntity;
import com.common.retrofit.method.ShaiDanMethods;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.rxbus.RxBus;
import com.common.rxbus.postevent.RxKeyEvent;
import com.common.utils.EmptyUtils;
import com.common.utils.SortUtils;
import com.common.widget.navigation.WidgetButton;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.xmkj.winmoney.R;
import com.xmkj.winmoney.bean.PicBean;
import com.xmkj.winmoney.my.adapter.PicTabAdapter;
import com.xmkj.winmoney.utils.CreateBmpFactory;
import com.xmkj.winmoney.utils.GraphicsBitmapUtils;
import com.xmkj.winmoney.utils.HandlerHelper;
import com.xmkj.winmoney.utils.HttpURLConnHelper;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Create by leo
 * 创建日期：2018/5/11
 * 描述：
 */

public class PublishShareActivity extends BaseMvpActivity implements PicTabAdapter.PicItemClickLisener {
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_qihao)
    EditText etQihao;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.rv_pic)
    RecyclerView rvPic;
    @BindView(R.id.iv_add)
    ImageView ivAdd;

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_share_dongtai;
    }

    @Override
    protected void onViewCreated() {
        setRightNavigationText();
    }
    /**
     * 设置右边文字
     */
    protected void setRightNavigationText() {
        m_navigationBar.setVisibility(View.VISIBLE);
//        context.getResources().getString(R.string.alias_hint)
        WidgetButton widgetButton = new WidgetButton(this, context.getResources().getDrawable(R.mipmap.publish));
        widgetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(EmptyUtils.isEmpty(getEditTextStr(etTitle))||EmptyUtils.isEmpty(getEditTextStr(etName))||EmptyUtils.isEmpty(getEditTextStr(etContent))||EmptyUtils.isEmpty(getEditTextStr(etQihao))){
                    showToastMsg("请填写完整信息！");
                    return;
                }
         /*   if(ids.size()==0){
                showToastMsg("上传图片");
                return;
            }*/
                gotoPublishDongTaiHttp();

            }
        });
        m_navigationBar.setRightMenu(widgetButton);
    }

    @Override
    protected void onViewClicked(View view) {
        if(view.getId()==ivAdd.getId()){
            if (datas.size() == 8) {
                showToastMsg("最多添加8张照片");
                return;
            }
            picPosition = 8;
            if (mCreateBmpFactory == null) {
                mCreateBmpFactory = new CreateBmpFactory(this);
            }
            AndPermission.with(this)
                    .requestCode(105)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                    .rationale(mRationaleListener)
                    .send();
        }
    }

    private void gotoPublishDongTaiHttp() {
        showProgressingDialog();
        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                RxBus.getDefault().postSticky(new RxKeyEvent(RxKeyEvent.REFRESH_CIRCLE, true));
                showToastMsg("晒单成功");
                dismissProgressDialog();
                onBackPressed();
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });
        if (ids.size() == 0) {
            imgIds.append("");
        } else {
            for (int i = 0; i < ids.size(); i++) {
                if (i == ids.size() - 1) {
                    imgIds.append(ids.get(i));
                } else {
                    imgIds.append(ids.get(i) + ",");
                }
            }
        }

        ShaiDanMethods.getInstance().addSaidan(subscriber, uid,hashid,getEditTextStr(etTitle),getEditTextStr(etName),getEditTextStr(etQihao),getEditTextStr(etContent),imgIds.toString(),1);
        rxManager.add(subscriber);
    }

    @Override
    protected void doLogicFunc() {
        attachClickListener(ivAdd);
        initRvPic();
    }


    @Override
    protected void setNavigation() {
        setNavigationBack("添加");
    }
    private StringBuffer imgIds = new StringBuffer();
    ArrayList<PicBean> datas = new ArrayList<>();
    private PicTabAdapter rvPicAdapter;
    List<String> ids = new ArrayList();
    @Override
    public void bindKnife() {
        ButterKnife.bind(this);
    }

    private void initRvPic() {
        GridLayoutManager layoutManager = new GridLayoutManager(context, 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvPic.setLayoutManager(layoutManager);
        if (rvPicAdapter == null) {
            rvPicAdapter = new PicTabAdapter(datas, context);
        }
        rvPic.setAdapter(rvPicAdapter);
        rvPicAdapter.setItemClickLister(this);
    }
    private int picPosition = 8;

    private RationaleListener mRationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
            new AlertDialog.Builder(PublishShareActivity.this)
                    .setTitle("友好提醒")
                    .setMessage("没有权限您不能使用相机，请把相机权限赐给我吧!(如果设置不再提示,您可以在设置中打开权限)")
                    .setPositiveButton("好，给你", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.resume();// 用户同意继续申请。
                        }
                    })
                    .setNegativeButton("我拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.cancel(); // 用户拒绝申请。
                        }
                    }).show();
        }
    };
    //点击头像弹出popwindow
    private PicPopupWindow popupWindow;
    //存储头像
    private String filePath = "";
    private CreateBmpFactory mCreateBmpFactory;
    private Bitmap bmp;
    public static final int REQUEST_CODE_CAMERA = 1000;
    public static final int REQUEST_CODE_GALLERY = 1001;
    private TextView tv_cancel;
    private TextView tv_camera;
    private TextView tv_photo;

    @Override
    public void onItemClick(int position) {
        picPosition = position;
//        if (datas.size() == 8) {
//            showToastMsg("最多上传8张照片");
//            return;
//        }
        if (mCreateBmpFactory == null) {
            mCreateBmpFactory = new CreateBmpFactory(this);
        }
        AndPermission.with(this)
                .requestCode(105)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .rationale(mRationaleListener)
                .send();
    }

    public class PicPopupWindow extends PopupWindow {
        public PicPopupWindow(Context mContext, View parent) {
            View view = View.inflate(PublishShareActivity.this, R.layout.pop_payback_select, null);
            tv_photo = (TextView) view.findViewById(R.id.tv_plan_repayment);//相册
            tv_photo.setText("相册");
            tv_camera = (TextView) view.findViewById(R.id.tv_plan_consume);//相机
            tv_camera.setText("相机");
            tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            tv_camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            filePath = resultList.get(0).getPhotoPath();
                            bmp = mCreateBmpFactory.getBitmapByOpt(filePath);
//                            if (picPosition != 8) {
//                                datas.set(picPosition, new PicBean(bmp));
//                                rvPicAdapter.notifyDataSetChanged();
//                                initRvPic();
//                            } else {
//                                PicBean picBean = new PicBean();
//                                picBean.bitPic = bmp;
//                                datas.add(picBean);
//                                rvPicAdapter.notifyDataSetChanged();
//                                initRvPic();
//                            }


                            if (picPosition < 8) {  //修改照片
                                datas.set(picPosition, new PicBean(bmp));
                                rvPicAdapter.notifyDataSetChanged();
                                initRvPic();
                            } else if (picPosition == 8) {  //添加照片
                                PicBean picBean = new PicBean();
                                picBean.bitPic = bmp;
                                datas.add(picBean);
                                rvPicAdapter.notifyDataSetChanged();
                                initRvPic();
                            } else { //修改用户图像

                            }

//                            ivFacePic.setImageBitmap(bmp);
                            //上传头像
                            if (!"".equals(filePath)) {
//                                setPicToNet(bmp);
//                                ivFacePic.setImageBitmap(bmp);
                                setPicToNet(bmp);
                            }
                            popupWindow.dismiss();
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {

                        }
                    });
                }
            });
            tv_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            tv_photo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, new GalleryFinal.OnHanlderResultCallback() {
                        @Override
                        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                            filePath = resultList.get(0).getPhotoPath();
                            bmp = mCreateBmpFactory.getBitmapByOpt(filePath);

                            if (picPosition < 8) {  //修改照片
                                datas.set(picPosition, new PicBean(bmp));
                                rvPicAdapter.notifyDataSetChanged();
                                initRvPic();
                            } else if (picPosition == 8) {  //添加照片
                                PicBean picBean = new PicBean();
                                picBean.bitPic = bmp;
                                datas.add(picBean);
                                rvPicAdapter.notifyDataSetChanged();
                                initRvPic();
                            } else { //修改用户图像

                            }
                            //上传头像
                            if (!"".equals(filePath)) {
                                setPicToNet(bmp);
                            }
                            popupWindow.dismiss();
                        }

                        @Override
                        public void onHanlderFailure(int requestCode, String errorMsg) {

                        }
                    });
                }
            });
            view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_in_a));
            setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            setFocusable(true);
            showAsDropDown(view);
            setOutsideTouchable(true);
            setBackgroundDrawable(getResources().getDrawable(R.color.bg_title2));
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();
        }
    }

    // 将进行剪裁后的图片显示到UI界面上
    private void setPicToNet(final Bitmap bmp) {
        showProgressingDialog();
        new Thread() {
            @Override
            public void run() {
                byte[] photodata = GraphicsBitmapUtils.Bitmap2Bytes(bmp);
                Map parameters = new HashMap();
                String time = System.currentTimeMillis()+"" ;
                parameters.put("time", time);
                parameters.put("hash",  SortUtils.getMyHash("fileNameuploadFile","time"+time,"uid"+uid,"hashid"+hashid,"tags"));
                parameters.put("apiId", Constans.ANDROID_APP_ID);
                parameters.put("terminal", "3");
                parameters.put("fileName", "uploadFile");
                parameters.put("uid", ""+uid);
                parameters.put("hashid", hashid);
                parameters.put("tags", "");
                try {
//                    LogUtil.d(HttpUrl.uploadFace + "       -------->" + parameters + "-------->" + filePath + "-------->" + photodata + "-------->" + "utf-8");
                    String s = HttpURLConnHelper.doPostSubmitBody("http://xmap1802011.php.hzxmnet.com/api/Upload/uploadImg", parameters, filePath, photodata, "utf-8");
                    if (s != null) {
                        Message message = new Message();
                        message.obj = s;
                        message.what = 888;
                        handler.sendMessage(message);
                    } else {
                        dismissProgressDialog();
//                        ToastCommom.createToastConfig().ToastShow(CompileInfoActivity.this, "网络开小差啦,请稍后重试", getResources().getColor(R.color.white));
                        showToastMsg("请稍等");
                    }

                } catch (Exception e) {
//                    LogUtil.e("上传图片---" + e);
                    dismissProgressDialog();
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
    }


    UpLoadPicEntity upLoadPicEntity = new UpLoadPicEntity();
    private String face_id;
    private HandlerHelper handler = new HandlerHelper(this) {
        @Override
        protected void handleMessage(Object reference, Message msg) {
            switch (msg.what) {

                case 888:
                    dismissProgressDialog();

                    if (msg.obj != null) {
                        String res = msg.obj.toString();
                        if (upLoadPicEntity != null) {
                            try {
                                upLoadPicEntity = new Gson().fromJson(msg.obj.toString(), upLoadPicEntity.getClass());
                                if ("000000".equals(upLoadPicEntity.Code)) {
                                    showToastMsg("上传成功");


                                    if (picPosition > 10) {
                                        face_id = upLoadPicEntity.Data.imgid + "";
                                    }
                                    if (picPosition < 8) {//修改照片
                                        ids.set(picPosition, upLoadPicEntity.Data.imgid + "");
                                    }
                                    if (picPosition == 8) {//添加照片
                                        ids.add(upLoadPicEntity.Data.imgid + "");
                                    }
                                    //修改头像
//                                    circle_info_pic.setImageBitmap(bmp);
                                    //   GliderHelper.loadImage(filePath, circle_info_pic, null);
//                                    faceId = upLoadPicEntity.getData().getId() + "";
//                                    updataFace();
//                                    avatar = upLoadPicEntity.Data.avatar;
//                                    if(login_status==1){
//                                        SPUtils.setShareString(Constans.FACE_SHOPMAN,avatar);
//                                    }else if(login_status==2){
//                                        SPUtils.setShareString(Constans.FACE_SALES,avatar);
//                                    }
//                                    ImageLoaderUtils.display(ivAvatar,upLoadPicEntity.Data.path);
//                                    hash_choose_img = true;


                                } else {
                                    showToastMsg("请稍后再试");
                                    dismissProgressDialog();
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    break;
            }
        }
    };
    @PermissionYes(105)
    private void openPic() {
        popupWindow = new PicPopupWindow(this, ivAdd);
    }

    @PermissionNo(105)
    private void injectPic() {
        popupWindow.dismiss();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 只需要调用这一句，剩下的 AndPermission 自动完成。
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }
}
